package com.xyy.ec.pop.api.kingdinggmp.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.entity.SaveParam;
import com.kingdee.bos.webapi.entity.SaveResult;
import com.xyy.ec.pop.api.kingdinggmp.config.KingDingClient;
import com.xyy.ec.pop.api.kingdinggmp.dto.erp.*;
import com.xyy.ec.pop.api.kingdinggmp.dto.pop.*;
import com.xyy.ec.pop.api.kingdinggmp.enums.K3FromEnum;
import com.xyy.ec.pop.api.kingdinggmp.helpers.ErpHelper;
import com.xyy.ec.pop.api.kingdinggmp.helpers.PopHelper;
import com.xyy.ec.pop.api.kingdinggmp.service.KingDingService;
import com.xyy.ec.pop.api.kingdinggmp.utils.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class kingDingServiceImpl implements KingDingService {

    @Autowired
    private KingDingClient kingDingClient;

    @Autowired
    private KingDingService kingDingService;

    @Override
    public List<GmpStockDto> queryGmpStock(String erpCodes, String syncWarehouse) {
        QueryParam queryParam = new QueryParam<>();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(GmpStockDto.class));
        queryParam.setFormId(K3FromEnum.QUERY_GMP_STOCK.getCode());
        if (StrUtil.isNotBlank(erpCodes)) {
            queryParam.setFilterString("F_RPIHInvStockQty>0 and FNumber in ( " + erpCodes + ")" + " and F_RPIHFStockName in( " + syncWarehouse + ") and F_RECN_SCJ>0");
        }

        List<GmpStockDto> gmpStockDtoList = new ArrayList<>();
        try {
            gmpStockDtoList = kingDingClient.executeBillQuery(queryParam, GmpStockDto.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return gmpStockDtoList;
    }

    /**
     * 查询客户列表
     *
     * @return 客户信息
     */
    @Override
    public List<GmpCustomerDto> queryGmpCustomer(Boolean isFullSync) {
        QueryParam queryParam = new QueryParam<>();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(GmpCustomerDto.class));
        queryParam.setFormId(K3FromEnum.GMP_CUSTOMER.getCode());
        queryParam.setFilterString("FDocumentStatus='C'");
        if (!isFullSync) {
            queryParam.setOrderString("FCUSTID desc");
            queryParam.setLimit(2000);
        }
        List<GmpCustomerDto> gmpCustomerDtoList = new ArrayList<>();
        try {
            gmpCustomerDtoList = kingDingClient.executeBillQuery(queryParam, GmpCustomerDto.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return gmpCustomerDtoList;
    }

    /**
     * @param popCustomers
     * @return
     */
    @Override
    public List<SellerCustomerCallBackDto> saveCustomer(List<PlatformCustomerDto> popCustomers, Map<String, String> customerCfgMap) {
        List<ErpCustomerDto> erpCustomerDtoList = ErpHelper.popToErpCustomerConvert(popCustomers, customerCfgMap);
        List<SellerCustomerCallBackDto> sellerCustomerCallBackDtoList = new ArrayList<>();
        for (ErpCustomerDto erpCustomerDto : erpCustomerDtoList) {
            SaveParam<ErpCustomerDto> saveParam = new SaveParam<>(erpCustomerDto);
            try {

                SaveResult save = kingDingClient.save(K3FromEnum.GMP_CUSTOMER.getCode(), saveParam);
                if (save.isSuccessfully() || JSON.toJSONString(save).contains("客户名称唯一")) {
                    SellerCustomerCallBackDto sellerCustomerCallBackDto = new SellerCustomerCallBackDto();
                    sellerCustomerCallBackDto.setId(Long.valueOf(erpCustomerDto.getFDescription().replace("药帮忙自动推送", "")));
                    sellerCustomerCallBackDto.setNo(erpCustomerDto.getFName());
                    sellerCustomerCallBackDto.setResult(true);
                    sellerCustomerCallBackDto.setOrgId(customerCfgMap.get("orgId"));
                    sellerCustomerCallBackDtoList.add(sellerCustomerCallBackDto);
                } else {
                    log.warn("金蝶客户导入异常错误信息: {}", JSON.toJSONString(save));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sellerCustomerCallBackDtoList;
    }

    /**
     * @param customerCfgMap
     * @return
     */
    @Override
    public List<ErpSkuInfoDto> queryErpSkuInfo(Map<String, String> customerCfgMap) {
        QueryParam queryParam = new QueryParam();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(ErpSkuInfoDto.class));
        queryParam.setFormId(K3FromEnum.SKU_INFO.getCode());
        queryParam.setFilterString("F_RECN_SCJ>0");
        List<ErpSkuInfoDto> erpSkuInfoDtos = new ArrayList<>();
        try {
            erpSkuInfoDtos = kingDingClient.executeBillQuery(queryParam, ErpSkuInfoDto.class);
        } catch (Exception e) {
            log.warn("kingDingServiceImpl.queryErpSkuInfo#金蝶商品信息查询异常： {}", JSON.toJSONString(queryParam));
            throw new RuntimeException(e);
        }
        return erpSkuInfoDtos;
    }

    /**
     * @param erpCodes
     * @return
     */
    @Override
    public List<ErpSkuInfoDto> queryErpSkuPriceInfo(String erpCodes) {
        QueryParam queryParam = new QueryParam<>();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(ErpSkuInfoDto.class));
        queryParam.setFormId(K3FromEnum.SKU_INFO.getCode());
        if (StrUtil.isNotBlank(erpCodes)) {
            queryParam.setFilterString("FNumber in ( " + erpCodes + ") and F_RECN_SCJ>0");
        }

        List<ErpSkuInfoDto> erpSkuInfoDtoList = new ArrayList<>();
        try {
            erpSkuInfoDtoList = kingDingClient.executeBillQuery(queryParam, ErpSkuInfoDto.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return erpSkuInfoDtoList;
    }

    /**
     * @param erpCode
     * @return
     */
    @Override
    public ErpSkuInfoDto queryErpSkuInfo(String erpCode) {
        QueryParam queryParam = new QueryParam();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(ErpSkuInfoDto.class));
        queryParam.setFormId(K3FromEnum.SKU_INFO.getCode());
        queryParam.setFilterString("FNumber in ( '" + erpCode + "') and F_RECN_SCJ>0");
        List<ErpSkuInfoDto> erpSkuInfoDtos = new ArrayList<>();
        try {
            erpSkuInfoDtos = kingDingClient.executeBillQuery(queryParam, ErpSkuInfoDto.class);
        } catch (Exception e) {
            log.warn("kingDingServiceImpl.queryErpSkuInfo#金蝶商品信息查询异常： {}", JSON.toJSONString(queryParam));
            throw new RuntimeException(e);
        }
        return erpSkuInfoDtos.get(0);
    }

    /**
     * @param orderInfoList
     * @return
     */
    @Override
    public List<SellerOrderCallBackDto> saveOrderInfo(List<SellerOrderInfoDto> orderInfoList, Map<String, String> orderConfig) {
        ErpOrderDto erpOrderDto = new ErpOrderDto();
        for (SellerOrderInfoDto popOrder : orderInfoList) {
            erpOrderDto.setFBILLNO(popOrder.getOrderNo());
            erpOrderDto.setFCustId(MapUtil.of("FNUMBER", popOrder.getVenderCode()));
            erpOrderDto.setFCONTACTID(popOrder.getPickName());
            erpOrderDto.setFTel(popOrder.getPickPhone());
            // 业务员
            erpOrderDto.setFSalerId(MapUtil.of("FSTAFFNUMBER", orderConfig.get("FSalerId")));
            // 销售员
            erpOrderDto.setFBUSINESSERID(MapUtil.of("FSTAFFNUMBER", orderConfig.get("FBusinessId")));
            // 备注
            erpOrderDto.setFNote("药帮忙单号【" + popOrder.getOrderNo() + "】");
            erpOrderDto.setF_RPIH_Remarks(popOrder.getPickAddress());
            // 商品明细
            List<SellerOrderDetailDto> sellerOrderDetailLists = popOrder.getSellerOrderDetailLists();
            List<ErpOrderDetailDto> erpOrderDetailDtoList = new ArrayList<>();
            for (SellerOrderDetailDto popOrderDetail : sellerOrderDetailLists) {
                ErpOrderDetailDto erpOrderDetailDto = new ErpOrderDetailDto();
                ErpSkuInfoDto erpSkuInfoDto = kingDingService.queryErpSkuInfo(popOrderDetail.getErpCode());
                if (erpSkuInfoDto == null) {
                    log.warn("订单号:{} {}未查询到商品信息", popOrderDetail.getOrderNo(), popOrderDetail.getErpCode());
                    continue;
                }
                erpOrderDetailDto.setFMaterialId(MapUtil.of("FNUMBER", popOrderDetail.getErpCode()));
                erpOrderDetailDto.setFUnitID(MapUtil.of("FNUMBER", erpSkuInfoDto.getFBaseUnitId_Fname()));
                erpOrderDetailDto.setFEntryQty(popOrderDetail.getPurchaseNumDecimal());
                erpOrderDetailDto.setFStockID(MapUtil.of("FNUMBER", "01"));
                erpOrderDetailDto.setFEntryNote(String.valueOf(popOrderDetail.getOrderDetailId()));
                erpOrderDetailDto.setF_RPIH_HighPrice(popOrderDetail.getSkuPayPrice());
                erpOrderDetailDto.setF_RPIH_HighAmount(popOrderDetail.getSkuPayPrice().multiply(popOrderDetail.getPurchaseNumDecimal()));
                erpOrderDetailDtoList.add(erpOrderDetailDto);
            }
            erpOrderDto.setF_RPIH_Entity(erpOrderDetailDtoList);
        }
        SaveParam<ErpOrderDto> saveParam = new SaveParam<>(erpOrderDto);
        List<SellerOrderCallBackDto> sellerOrderCallBackDtoList = new ArrayList<>();
        try {
            SaveResult save = kingDingClient.save(K3FromEnum.SAVA_GMP_ORDER.getCode(), saveParam);
            if (save.isSuccessfully()) {
                SellerOrderCallBackDto sellerOrderCallBackDto = new SellerOrderCallBackDto();
                sellerOrderCallBackDto.setOrderNo(erpOrderDto.getFBILLNO());
                sellerOrderCallBackDto.setType(1);
                sellerOrderCallBackDto.setResult(true);
                sellerOrderCallBackDto.setOrgId(orderConfig.get("orgId"));
                sellerOrderCallBackDtoList.add(sellerOrderCallBackDto);
            } else {
                log.warn("金蝶订单导入异常错误信息: {} 导入数据: {}", JSON.toJSONString(save), JSON.toJSONString(saveParam));
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sellerOrderCallBackDtoList;
    }

    /**
     * @param order
     * @return
     */
    @Override
    public List<SellerOrderDeliverDetailForErpDto> queryOutOrderList(String order) {
        QueryParam queryParam = new QueryParam();
        queryParam.setFieldKeys(ClassUtils.getClassNameList(ErpOutOrderDto.class));
        queryParam.setFormId(K3FromEnum.QUERY_OUT_ORDER.getCode());
        queryParam.setFilterString("F_RPIH_SourceBillNo='" + order + "'");
        List<ErpOutOrderDto> erpOutOrderDtos = new ArrayList<>();
        try {
            erpOutOrderDtos = kingDingClient.executeBillQuery(queryParam, ErpOutOrderDto.class);
        } catch (Exception e) {
            log.warn("kingDingServiceImpl.queryOutOrderList#金蝶出库信息查询异常： {}", JSON.toJSONString(queryParam));
            throw new RuntimeException(e);
        }
        return PopHelper.erpToPopOutOrder(erpOutOrderDtos);
    }

}
